package com.dayu.finecomm.handler.cmd;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.socket.DatagramPacket;

import java.net.InetSocketAddress;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.dayu.finecomm.protocol.SpecialCareChannelInboundAdapter;
import com.dayu.finecomm.protocol.pojo.TPacket;
import com.dayu.finecomm.protocol.pojo.TStation;
import com.dayu.finecomm.source.CollectSource;
import com.dayu.finecomm.utils.Helpers;

/**
 * ycb指令下发
 * 
 * @author Chenjiawei
 *
 */
public class CMDYcbSendHandler extends
		SpecialCareChannelInboundAdapter<TPacket> {

	static Logger LOGGER = LoggerFactory.getLogger(CMDYcbSendHandler.class);

	CollectSource source;

	public CMDYcbSendHandler(CollectSource source) {
		this.source = source;
	}

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, TPacket packet)
			throws Exception {

		TStation station = source.collection().get(packet.id());

		if (station != null) {

			String commandString = null;

			if ((commandString = station.historyCommand.poll()) != null) {

				Thread.sleep(1000);

				send(station.udp, station.address, ctx, 1, station.id,
						commandString);
			}
		}

		ctx.fireChannelRead(packet);
	}

	/**
	 * 
	 * @param udp
	 *            是否udp方式
	 * @param address
	 *            地址
	 * @param ctx
	 *            通道
	 * @param count
	 *            次数
	 * @param station
	 *            站号
	 * @param commandString
	 *            下发的指令
	 */
	public static void send(boolean udp, InetSocketAddress address,
			final ChannelHandlerContext ctx, int count, String station,
			String commandString) {

		if (commandString != null && station != null) {

			byte[] msg;

			LOGGER.info(String.format(count + " Send command to %s: %s",
					station, JSON.toJSONString(commandString)));

			msg = Helpers.hexToBytes(commandString);

			if (udp) {
				ctx.writeAndFlush(new DatagramPacket(
						Unpooled.copiedBuffer(msg), address));
			} else {
				ctx.writeAndFlush(Unpooled.copiedBuffer(msg));

			}
		}

	}

}
